#include "tools.h"



QSqlDatabase connectToDatabase() {
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("chat_system");
    db.setUserName("root");
    db.setPassword("123456");

    if (!db.open()) {
        qDebug() << "数据库连接失败: " << db.lastError().text();
        return QSqlDatabase();
    }
    qDebug() << "数据库连接成功";
    return db;
}

bool findUserByUsername(const QString &username,  User &user) {
    QSqlDatabase db = connectToDatabase();
    if (!db.isOpen()) {
        qDebug()<<"数据库已关闭";
        return false;
    }
    qDebug()<<"查询数据："<<"username="<<username;
    QSqlQuery query;
    query.prepare("SELECT * FROM user WHERE username = :username");
    query.bindValue(":username", username);

    if (query.exec()) {
        if (query.next()) {  // 确保结果集中有数据
            user.setId(query.value("id").toInt());
            user.setUsername(query.value("username").toString());
            user.setPassword(query.value("password").toString());
            user.setGender(query.value("gender").toString());
            user.setAge(query.value("age").toInt());
            user.setPhone(query.value("phone").toString());
            user.setState(query.value("state").toString());
            user.setNote(query.value("note").toString());
            qDebug() << "数据：" << user.toQString();
            qDebug() << "sql语句: " << query.lastQuery();
            db.close();
            return true;
        } else {
            // 查询结果为空，返回空的 User
            qDebug() << "没有找到用户";
            // 你可以在此处将 user 设置为空或清除已有数据
            user = User();  // 重置 User 对象
            db.close();
            return false;
        }
    } else {
        qDebug() << "查询失败: " << query.lastError().text();
        db.close();
        return false;
    }
    db.close();
}

bool insertUser(const  User &user) {
    QSqlDatabase db = connectToDatabase();
    if (!db.isOpen()) return false;

    qDebug() << "插入数据："<<user.toQString();
    QSqlQuery query;
    query.prepare("INSERT INTO user (username, password, gender, age, phone, state, note) "
                  "VALUES (:username, :password, :gender, :age, :phone, :state, :note)");
    query.bindValue(":username", user.getUsername());
    query.bindValue(":password", user.getPassword());
    query.bindValue(":gender", user.getGender());
    query.bindValue(":age", user.getAge());
    query.bindValue(":phone", user.getPhone());
    query.bindValue(":state", "离线");
    query.bindValue(":note", user.getNote());

    if (query.exec()) {
        qDebug() << "插入成功！";
        db.close();
        return true;
    } else {
        qDebug() << "插入失败: " << query.lastError().text();
        db.close();
    }

    return false;
}

bool updateUser(const  User &user) {
    QSqlDatabase db = connectToDatabase();
    if (!db.isOpen()) return false;

    QSqlQuery query;
    query.prepare("UPDATE user SET password = :password, gender = :gender, age = :age, phone = :phone, "
                  "state = :state, note = :note WHERE username = :username");
    query.bindValue(":username", user.getUsername());
    query.bindValue(":password", user.getPassword());
    query.bindValue(":gender", user.getGender());
    query.bindValue(":age", user.getAge());
    query.bindValue(":phone", user.getPhone());
    query.bindValue(":state", user.getState());
    query.bindValue(":note", user.getNote());

    if (query.exec()) {
        qDebug() << "更新成功！";
        db.close();
        return true;
    } else {
        qDebug() << "更新失败: " << query.lastError().text();
        db.close();
    }
    return false;
}

bool deleteUser(const QString &username) {
    QSqlDatabase db = connectToDatabase();
    if (!db.isOpen()) return false;

    QSqlQuery query;
    query.prepare("DELETE FROM user WHERE username = :username");
    query.bindValue(":username", username);

    if (query.exec()) {
        qDebug() << "删除成功！";
        db.close();
        return true;
    } else {
        qDebug() << "删除失败: " << query.lastError().text();
        db.close();
    }
    return false;
}

bool isFriendExist(const QString &username1, const QString &username2) {
    QSqlDatabase db = connectToDatabase();
    if (!db.isOpen()) {
        qDebug() << "数据库已关闭";
        return false;
    }
    QSqlQuery query;
    query.prepare("SELECT COUNT(*) FROM friend WHERE (username1 = :username1 AND username2 = :username2) "
                  "OR (username1 = :username2 AND username2 = :username1)");
    query.bindValue(":username1", username1);
    query.bindValue(":username2", username2);

    if (query.exec()) {
        if (query.next()) {
            int count = query.value(0).toInt();
            return count > 0;  // 如果 count > 0，说明存在记录
        }
    } else {
        qDebug() << "查询失败: " << query.lastError().text();
    }
    db.close();
    return false;
}

QString insertFriend(const QString &username1, const QString &username2) {
    QSqlDatabase db = connectToDatabase();
    if (!db.isOpen()) {
        return "服务端数据库连接中断";
    }

    // 先检查是否已经是好友
    if (isFriendExist(username1, username2)) {
        qDebug()<<"好友已存在";
        return "好友已存在";
    }

    QSqlQuery query;

    // 插入 username1, username2 关系
    query.prepare("INSERT INTO friend (username1, username2) VALUES (:username1, :username2)");
    query.bindValue(":username1", username1);
    query.bindValue(":username2", username2);

    if (query.exec()) {
        // 插入成功后，再插入反向的记录
        query.prepare("INSERT INTO friend (username1, username2) VALUES (:username2, :username1)");
        query.bindValue(":username1", username1);
        query.bindValue(":username2", username2);

        if (query.exec()) {
            return "添加成功！";
        } else {
            qDebug() << "插入反向记录失败: " << query.lastError().text();
            return "添加失败！";
        }
    } else {
        qDebug() << "插入失败: " << query.lastError().text();
        return "添加失败！";
    }
}

QString deleteFriend(const QString &username1, const QString &username2) {
    QSqlDatabase db = connectToDatabase();
    if (!db.isOpen()) {
        return "数据库已关闭";
    }

    // 先检查是否是好友
    if (!isFriendExist(username1, username2)) {
        return "好友关系不存在";
    }

    QSqlQuery query;

    // 删除 username1, username2 关系
    query.prepare("DELETE FROM friend WHERE (username1 = :username1 AND username2 = :username2) "
                  "OR (username1 = :username2 AND username2 = :username1)");
    query.bindValue(":username1", username1);
    query.bindValue(":username2", username2);

    if (query.exec()) {
        return "删除成功";
    } else {
        qDebug() << "删除失败: " << query.lastError().text();
        return "删除失败";
    }
}

bool addGroup(const QString& username1, const QString& groupName, const QString& username2) {
    QSqlDatabase db = connectToDatabase();
    if (!db.isOpen()) {
        return false;
    }

    // 防止插入重复的分组记录
    QSqlQuery query(db);
    query.prepare("INSERT INTO `group` (username1, group_name, username2) VALUES (:username1, :group_name, :username2)");
    query.bindValue(":username1", username1);
    query.bindValue(":group_name", groupName);
    query.bindValue(":username2", username2);

    if (!query.exec()) {
        qDebug() << "添加分组失败：" << query.lastError().text();
        db.close();
        return false;
    }
    db.close();
    return true;
}

bool deleteGroup(const QString &username1, const QString &username2) {
    QSqlDatabase db = connectToDatabase();
    if (!db.isOpen()) return false;

    QSqlQuery query;
    query.prepare("DELETE FROM `group` WHERE username1 = :username1 AND username2 = :username2");
    query.bindValue(":username1", username1);
    query.bindValue(":username2", username2);

    if (query.exec()) {
        qDebug() << "删除分组成功！";
        db.close();
        return true;
    } else {
        qDebug() << "删除分组失败: " << query.lastError().text();
        db.close();
    }
    return false;
}

void processDatabase(const QByteArray &data,QTcpSocket *clientSocket){
    //用流处理
    QDataStream in(data);
    in.setByteOrder(QDataStream::LittleEndian);
    quint8 packetType;//包类型
    quint8 operationType;//操作类型
    quint8 tableType;//表类型
    in>>packetType;
    in>>operationType;
    in>>tableType;
    qDebug()<<"packetType = "<<packetType;
    qDebug()<<"operationType = "<<operationType;
    qDebug()<<"tableType = "<<tableType;

    switch(operationType){
    case Select:{
        switch(tableType){
        case table_user:{
            User user;
            //从流中读出user
            getUserByStream(in,user);
            //从数据库中读
            qDebug()<<"从数据库中读";
            if(!findUserByUsername(user.getUsername(),user)){
                qDebug()<<"从数据库中读取失败";
            }
            else {
                qDebug()<<"从数据库中读取成功";
                //向客户端发送数据
                sendUserData(clientSocket,user);
            }
            break;
        }
        case table_friend:{
            QString username;
            //从流中读出username;
            in>>username;
            //从数据库中读
            QStringList usernames;
            findFriendByUsername(username,usernames);
            //发送数据
            if (!clientSocket || !clientSocket->isOpen()) {
                qWarning() << "Socket is not open!";
                return;
            }
            // 序列化数据
            QByteArray data;
            QDataStream out(&data, QIODevice::WriteOnly);
            out.setByteOrder(QDataStream::LittleEndian);

            // 将list对象的属性写入流中
            out <<usernames;

            // 发送数据
            clientSocket->write(data);
            break;
        }
        case table_group:{
            QString username,groupname;
            in>>username>>groupname;
            QStringList friendnames;
            findFriendByUsernameAndGroupname(username,groupname,friendnames);
            //发送数据
            if (!clientSocket || !clientSocket->isOpen()) {
                qWarning() << "Socket is not open!";
                return;
            }
            // 序列化数据
            QByteArray data;
            QDataStream out(&data, QIODevice::WriteOnly);
            out.setByteOrder(QDataStream::LittleEndian);

            // 将list对象的属性写入流中
            out <<friendnames;

            // 发送数据
            clientSocket->write(data);
            break;
        }
        case table_groupname:{
            QString username;
            //从流中读出username;
            in>>username;
            //从数据库中读
            QStringList groupnames;
            findGroupNameByUsername(username,groupnames);
            //发送数据
            if (!clientSocket || !clientSocket->isOpen()) {
                qWarning() << "Socket is not open!";
                return;
            }
            // 序列化数据
            QByteArray data;
            QDataStream out(&data, QIODevice::WriteOnly);
            out.setByteOrder(QDataStream::LittleEndian);

            // 将list对象的属性写入流中
            out <<groupnames;

            // 发送数据
            clientSocket->write(data);
            break;
        }
        default:{
            break;
        }
        }
        break;
    }
    case Update:{
        switch(tableType){
        case table_user:{
            break;
        }
        case table_friend:{
            break;
        }
        case table_group:{
            break;
        }
        default:{
            break;
        }
        }
        break;
        break;
    }
    case Delete:{
        switch(tableType){
        case table_friend:{
            //删除好友关系
            QString username1,username2;
            in>>username1>>username2;
            QString res= deleteFriend(username1,username2);
            // 序列化数据
            QByteArray data;
            QDataStream out(&data, QIODevice::WriteOnly);
            out.setByteOrder(QDataStream::LittleEndian);

            // 将res写入流中
            out <<res;
            // 发送数据
            clientSocket->write(data);
        }

        case table_groupname:{
            //删除分组名
            //读出数据
            QString username,groupname;
            in>>username>>groupname;
            QString res;
            deleteGroupName(username,groupname,res);
            // 序列化数据
            QByteArray data;
            QDataStream out(&data, QIODevice::WriteOnly);
            out.setByteOrder(QDataStream::LittleEndian);

            // 将res写入流中
            out <<res;
            // 发送数据
            clientSocket->write(data);
            break;
        }

        case table_group:{
            QString username1,groupname,username2,res;
            in>>username1>>groupname>>username2;
            deleteGroup(username1,groupname,username2,res);

            // 序列化数据
            QByteArray data;
            QDataStream out(&data, QIODevice::WriteOnly);
            out.setByteOrder(QDataStream::LittleEndian);

            // 将res写入流中
            out <<res;
            // 发送数据
            clientSocket->write(data);
            break;
        }
        default:{
            break;
        }
        }
        break;
    }
    case Insert:{
        switch(tableType){
        case table_user:{
            User user;
            //从流中读出user
            getUserByStream(in,user);
            //写入数据库
            qDebug()<<"写入数据库";
            qDebug()<<user.toQString();
            if(!insertUser(user)){
                qDebug()<<"写入数据库失败";
            }
            else {
                qDebug()<<"写入数据库成功";
                //向客户端发送数据
                if (!clientSocket || !clientSocket->isOpen()) {
                    qWarning() << "Socket is not open!";
                    return;
                }
                // 序列化用户数据
                QByteArray data;
                QDataStream out(&data, QIODevice::WriteOnly);
                out.setByteOrder(QDataStream::LittleEndian);
                QString res="注册成功";
                out<<res;
                clientSocket->write(data);
            }
            break;
        }
        case table_friend:{
            //插入好友关系
            //读出数据
            QString username1,username2;
            in>>username1>>username2;
            QString res= insertFriend(username1,username2);
            // 序列化数据
            QByteArray data;
            QDataStream out(&data, QIODevice::WriteOnly);
            out.setByteOrder(QDataStream::LittleEndian);

            // 将res写入流中
            out <<res;
            // 发送数据
            clientSocket->write(data);
            break;
        }
        case table_group:{
            QString username1,groupname,username2,res;
            in>>username1>>groupname>>username2;
            insertGroup(username1,groupname,username2,res);

            // 序列化数据
            QByteArray data;
            QDataStream out(&data, QIODevice::WriteOnly);
            out.setByteOrder(QDataStream::LittleEndian);

            // 将res写入流中
            out <<res;
            // 发送数据
            clientSocket->write(data);
            break;
        }
        case table_groupname:{
            //添加分组名
            //读出数据
            QString username,groupname;
            in>>username>>groupname;
            QString res;
            insertGroupName(username,groupname,res);
            // 序列化数据
            QByteArray data;
            QDataStream out(&data, QIODevice::WriteOnly);
            out.setByteOrder(QDataStream::LittleEndian);

            // 将res写入流中
            out <<res;
            // 发送数据
            clientSocket->write(data);
            break;
        }
        default:{
            break;
        }
        }
        break;
        break;
    }
    default:{
        break;
    }
    }


}

void getUserByStream(QDataStream &in, User &user){
    int id;   //id
    QString username; //用户名
    QString password; //密码
    QString gender; //性别
    int age; //年龄
    QString phone; //电话号码
    QString state; //状态
    QString note; //个人说明

    in>>id>>username>>password>>gender>>age>>phone>>state>>note;

    user.setId(id);
    user.setUsername(username);
    user.setPassword(password);
    user.setGender(gender);
    user.setAge(age);
    user.setPhone(phone);
    user.setState(state);
    user.setNote(note);
    qDebug()<<"读取到数据："<<user.toQString();
}

void sendUserData(QTcpSocket* socket, const User& user) {
    if (!socket || !socket->isOpen()) {
        qWarning() << "Socket is not open!";
        return;
    }
    // 序列化用户数据
    QByteArray data;
    QDataStream out(&data, QIODevice::WriteOnly);
    out.setByteOrder(QDataStream::LittleEndian);

    // 将User对象的属性写入流中
    out << user.getId() << user.getUsername() << user.getPassword() <<user.getGender()<<user.getAge()<<user.getPhone()<<user.getState()<<user.getNote();

    // 发送数据
    socket->write(data);

    if (socket->waitForBytesWritten()) {
        qDebug() << "服务端用户数据发送成功.";
    } else {
        qWarning() << "服务端用户数据发送失败.";
    }
}

void getFriendByStream(QDataStream &in,Friend &frd){
    int id;          // 好友关系记录的id
    QString username1; // 主用户名
    QString username2; // 从属用户名
    in>>id>>username1>>username2;
    frd.setId(id);
    frd.setUsername1(username1);
    frd.setUsername2(username2);
}

void sendFriendData(QTcpSocket* socket, const Friend &frd){
    if (!socket || !socket->isOpen()) {
        qWarning() << "Socket is not open!";
        return;
    }
    // 序列化用户数据
    QByteArray data;
    QDataStream out(&data, QIODevice::WriteOnly);
    out.setByteOrder(QDataStream::LittleEndian);

    // 将User对象的属性写入流中
    out << frd.getId() << frd.getUsername1() << frd.getUsername2();

    // 发送数据
    socket->write(data);

    if (socket->waitForBytesWritten()) {
        qDebug() << "User data sent successfully.";
    } else {
        qWarning() << "Failed to send user data.";
    }
}

void waitForTimeout(int milliseconds) {
    QEventLoop loop;
    QTimer::singleShot(milliseconds, &loop, &QEventLoop::quit); // 指定时间后退出事件循环
    loop.exec();  // 等待直到事件循环退出
    qDebug() << "等待" << milliseconds << "毫秒后退出";
}

bool findFriendByUsername(const QString &username,QStringList &usernames) {
    QSqlDatabase db = connectToDatabase();
    if (!db.isOpen()) return false;

    qDebug() << "查询"<<username<<"的好友";
    QSqlQuery query;
    query.prepare("SELECT username2 FROM friend WHERE (username1 = :username1)");
    query.bindValue(":username1", username);
    // 清空目标列表，确保每次调用时都是新的数据
    usernames.clear();

    // 遍历查询结果并将 username2 添加到 QStringList
    if (!query.exec()) {
        qDebug() << "查询失败:" << query.lastError().text();
        return false;
    }
    qDebug() << "查询成功:";
    // 查询到好友：
    while (query.next()) {
        QString username2 = query.value(0).toString();
        qDebug()<<username2;
        usernames.append(username2);
    }
    return true;
}

// 删除指定分组名的分组，传入用户名和分组名
bool deleteGroupByName(const QString &groupName) {
    QSqlDatabase db = connectToDatabase();
    if (!db.isOpen()) return false;

    QSqlQuery query;
    query.prepare("DELETE FROM `group` WHERE group_name = :group_name");
    query.bindValue(":group_name", groupName);

    if (query.exec()) {
        qDebug() << "删除分组成功！";
        return true;
    } else {
        qDebug() << "删除分组失败: " << query.lastError().text();
    }
    return false;
}

bool updateGroupName(const Group &group, const QString &newGroupName) {
    QSqlDatabase db = connectToDatabase();
    if (!db.isOpen()) return false;

    QSqlQuery query;
    query.prepare("UPDATE `group` SET group_name = :newGroupName WHERE id = :id");
    query.bindValue(":id", group.getId());
    query.bindValue(":newGroupName", newGroupName);

    if (query.exec()) {
        qDebug() << "修改分组名成功！";
        return true;
    } else {
        qDebug() << "修改分组名失败: " << query.lastError().text();
    }
    return false;
}


// 查询所有的分组名
void findGroupNameByUsername(const QString &username, QStringList &groupnames)
{
    QSqlDatabase db = QSqlDatabase::database(); // 获取默认数据库连接
    QSqlQuery query(db);
    // 从 groupname 表中查询所有 username = username 的 group_name 字段
    query.prepare("SELECT group_name FROM groupname WHERE username = :username");
    query.bindValue(":username", username);
    if (query.exec()) {
        while (query.next()) {
            groupnames.append(query.value(0).toString());
        }
    } else {
        qWarning() << "Query error: " << query.lastError().text();
    }
}

// 查询指定分组名
void findGroupName(const QString &username, const QString &groupname, QString &res)
{
    QSqlDatabase db = QSqlDatabase::database(); // 获取默认数据库连接
    QSqlQuery query(db);
    // 从 groupname 表中查询指定的 username = username，group_name = groupname 记录
    query.prepare("SELECT * FROM groupname WHERE username = :username AND group_name = :groupname");
    query.bindValue(":username", username);
    query.bindValue(":groupname", groupname);
    if (query.exec()) {
        if (query.next()) {
            res = "存在分组";
        } else {
            res = "不存在分组";
        }
    } else {
        qWarning() << "Query error: " << query.lastError().text();
        res = "查询失败";
    }
}

// 删除分组名记录
void deleteGroupName(const QString &username, const QString &groupname, QString &res)
{
    QString queryRes;
    findGroupName(username, groupname, queryRes);
    if (queryRes == "存在分组") {
        QSqlDatabase db = QSqlDatabase::database(); // 获取默认数据库连接
        QSqlQuery query(db);
        query.prepare("DELETE FROM groupname WHERE username = :username AND group_name = :groupname");
        query.bindValue(":username", username);
        query.bindValue(":groupname", groupname);
        if (query.exec()) {
            res = "删除成功";
        } else {
            qWarning() << "Delete error: " << query.lastError().text();
            res = "删除失败";
        }
    } else {
        res = "删除失败，分组不存在";
    }
}

// 添加分组名记录
void insertGroupName(const QString &username, const QString &groupname, QString &res)
{
    QString queryRes;
    findGroupName(username, groupname, queryRes);
    if (queryRes == "不存在分组") {
        QSqlDatabase db = QSqlDatabase::database(); // 获取默认数据库连接
        QSqlQuery query(db);
        query.prepare("INSERT INTO groupname (username, group_name) VALUES (:username, :groupname)");
        query.bindValue(":username", username);
        query.bindValue(":groupname", groupname);
        if (query.exec()) {
            res = "添加成功";
        } else {
            qWarning() << "Insert error: " << query.lastError().text();
            res = "添加失败";
        }
    } else {
        res = "添加失败，分组已存在";
    }
}








//根据指定用户查询好友
bool findFriendByUsernameAndGroupname(const QString &username, const QString &groupname, QStringList &friendnames) {
    QSqlDatabase db = connectToDatabase();
    if (!db.isOpen()) {
        qDebug() << "数据库未打开";
        return false;
    }

    // 查询分组的所有好友
    QSqlQuery query;
    query.prepare("SELECT username2 FROM `group` WHERE username1 = :username1 AND group_name = :groupname");
    query.bindValue(":username1", username);
    query.bindValue(":groupname", groupname);

    if (query.exec()) {
        // 清空结果列表
        friendnames.clear();

        while (query.next()) {
            // 将查询到的所有 username2 加入到 friendnames 列表中
            friendnames.append(query.value("username2").toString());
        }
        qDebug() << "查询结果：" << friendnames;
        return true;
    } else {
        qDebug() << "查询失败：" << query.lastError().text();
        return false;
    }
}

//查询指定的分组记录
bool findGroup(const QString &username1, const QString &groupname, const QString &username2, QString &res) {
    QSqlDatabase db = connectToDatabase();
    if (!db.isOpen()) {
        qDebug() << "数据库未打开";
        res = "数据库未连接";
        return false;
    }

    // 查询是否存在指定的分组记录
    QSqlQuery query;
    query.prepare("SELECT * FROM `group` WHERE username1 = :username1 AND group_name = :groupname AND username2 = :username2");
    query.bindValue(":username1", username1);
    query.bindValue(":groupname", groupname);
    query.bindValue(":username2", username2);

    if (query.exec()) {
        if (query.next()) {
            res = "存在分组关系";
            return true;
        } else {
            res = "不存在分组关系";
            return false;
        }
    } else {
        qDebug() << "查询失败：" << query.lastError().text();
        res = "查询失败";
        return false;
    }
}


//添加分组记录
void insertGroup(const QString &username1, const QString &groupname, const QString &username2, QString &res){
    //查询好友是否存在
    bool result= isFriendExist(username1, username2);
    if(!result){
        res = "不存在好友";
        return;
    }
    //查询分组名是否存在
    QString result2;
    findGroupName(username1,groupname,result2);
    qDebug()<<result2;
    if(result2=="不存在分组"){
        res = "不存在分组";
    }
    //判断是否存在分组关系记录
    QString findRes;
    if (findGroup(username1, groupname, username2, findRes)) {
        res = "已存在分组关系";
        return;
    }
    // 不存在，执行插入
    QSqlDatabase db = connectToDatabase();
    if (!db.isOpen()) {
        res = "数据库未连接";
        return;
    }
    QSqlQuery query;
    query.prepare("INSERT INTO `group` (username1, group_name, username2) VALUES (:username1, :groupname, :username2)");
    query.bindValue(":username1", username1);
    query.bindValue(":groupname", groupname);
    query.bindValue(":username2", username2);

    if (query.exec()) {
        res = "移入分组成功";
       } else {
           qDebug() << "插入分组失败: " << query.lastError().text();
           res = "移入分组失败";
       }

}


//接口：删除分组记录
void deleteGroup(const QString &username1, const QString &groupname, const QString &username2, QString &res){

    //查询好友是否存在
    bool result= isFriendExist(username1, username2);
    if(!result){
        res = "不存在好友";
        return;
    }
    //查询分组名是否存在
    QString result2;
    findGroupName(username1,groupname,result2);
    qDebug()<<result2;
    if(result2=="不存在分组"){
        res = "不存在分组";
    }
    //判断是否存在分组关系记录
    QString findRes;
    if (!findGroup(username1, groupname, username2, findRes)) {
        res = "不存在分组关系";
        return;
    }
    // 存在分组关系，直接执行删除操作
       QSqlDatabase db = connectToDatabase();
       if (!db.isOpen()) {
           res = "数据库未连接";
           return;
       }

       QSqlQuery query;
       query.prepare("DELETE FROM `group` WHERE username1 = :username1 AND group_name = :groupname AND username2 = :username2");
       query.bindValue(":username1", username1);
       query.bindValue(":groupname", groupname);
       query.bindValue(":username2", username2);

       if (query.exec()) {
           if (query.numRowsAffected() > 0) {
               res = "移出分组成功";
           } else {
               res = "移除分组失败";
           }
       } else {
           qDebug() << "删除分组失败: " << query.lastError().text();
           res = "移出分组失败";
       }
}

